import logging
import subprocess

from ocup.utils import is_efi

logger = logging.getLogger("ocup")


class Boot(object):
    def __init__(self):
        pass

    def fix_grub(self):
        if is_efi():
            logger.debug("not reinstall grub2 in efi")
        else:
            logger.debug("install grub2 in bios")
            self.fix_bios_grub()

    def fix_bios_grub(self):
        self.remake_grub_config()
        self.reinstall_grub_loader()

    @staticmethod
    def remake_grub_config():
        logger.info("remake grub config")
        cmd = ["/usr/sbin/grub2-mkconfig", "-o", "/etc/grub2.cfg"]
        try:
            result = subprocess.run(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
            if result.returncode:
                logger.error(result.stderr)
                logger.error(result.stdout)
        except Exception as e:
            logger.error(e)

    @staticmethod
    def reinstall_grub_loader():
        disk = None
        logger.info("get boot part")
        cmd = ["/usr/sbin/grub2-probe", "--target=device", "/boot"]
        result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if result.returncode:
            logger.error("get boot part failed")
            logger.error(result.stderr)
            return
        try:
            part = result.stdout.decode().strip().split("/")[-1]
            logger.debug("boot part is {}".format(part))
            with open("/proc/partitions") as f:
                partitions = f.read()
            logger.debug("partitions is {}".format(partitions))
            for i in partitions.splitlines():
                part_info = i.split()
                if len(part_info) != 4:
                    continue
                if part_info[0] == "major":
                    continue
                if part_info[1] == "0":
                    disk = part_info[3]
                if part_info[3] == part:
                    break
            logger.debug("boot disk is {}".format(disk))
        except Exception as e:
            logger.error(e)
            return

        if disk:
            logger.info("reinstall grub2")
            cmd = ["/usr/sbin/grub2-install", "/dev/{}".format(disk)]
            result = subprocess.run(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
            if result.returncode:
                logger.error(result.stderr)
                logger.error(result.stdout)
